package chapter24;


import java.io.ByteArrayOutputStream;
import java.io.FileInputStream;
import java.io.IOException;

/**
 * @author lzy
 * @version v1.0
 * Create DateTime: 2019/2/27 22:27
 */
public class MyClassLoader extends ClassLoader {
    private final String BASE_DIR;

    public MyClassLoader(String BASE_DIR) {
        this.BASE_DIR = BASE_DIR;
    }

    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        String fileName = name.replaceAll("\\.", "/");
        fileName = BASE_DIR + fileName + ".class";

        try (ByteArrayOutputStream out = new ByteArrayOutputStream();
             FileInputStream in = new FileInputStream(fileName)) {
            byte[] buffer = new byte[1024];
            int read = 0;
            while ((read = in.read(buffer)) != -1) {
                out.write(buffer, 0, read);
            }
            byte[] bytes = out.toByteArray();
            return defineClass(name, bytes, 0, bytes.length);
        } catch (IOException e) {
            throw new ClassNotFoundException("fail to load class " + name, e);
        }
    }
}
